from rest_framework import serializers

from oauth.utils import check_openid_token
from users.models import Users
from .models import OAuthQQUser
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadSignature,SignatureExpired
from django.conf import settings
from django_redis import get_redis_connection







#把用户id和 openid 保存起来
class QQAuthUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='操作凭证')
    # email
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    # class Meta:
    #     model = OAuthQQUser
    #     fields = []

    def validate(self, attrs):

        # 1. 验证 access_token
        access_token = attrs.get('access_token')

        # 检测 token
        openid = check_openid_token(access_token)

        if openid:
            attrs['openid'] = openid

        # 2. 验证短信验证码

        mobile = attrs.get('mobile')

        redis_conn = get_redis_connection('code')

        # 获取redis的code
        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code is None:
            raise serializers.ValidationError('验证码以过期')

        if redis_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码不一致')

        # 3. 需要根据手机号查询用户是否存在，如果用户存在 则判断密码是否正确
        # 如果用户不存在，则可以绑定
        try:
            user = Users.objects.get(mobile=mobile)
        except Users.DoesNotExist:
            # 不存在 可以绑定, 需要创建一个用户，创建用户的代码我们写在 create方法中
            pass
        else:
            # 存在,判断密码是否正确
            if not user.check_password(attrs.get('password')):
                raise serializers.ValidationError('密码不正确')

            attrs['user'] = user

        return attrs

    # data --> attrs --> validated_data

    def create(self, validated_data):

        # 我们最终要将 OAuthQQUser 中的 openid,user保存起来

        user = validated_data.get('user')

        if user is None:
            # 需要手动创建一个用户
            user = Users.objects.create(
                username=validated_data.get('mobile'),
                password=validated_data.get('password'),
                mobile=validated_data.get('mobile')
            )

            # 改密码
            user.set_password(validated_data.get('password'))
            user.save()

        # 最终将 OAuthQQUser 创建
        qquser = OAuthQQUser.objects.create(
            user=user,
            openid=validated_data.get('openid')
        )

        return user


